var CAS = function CAS(options) {
	options = options || {};
	if (!options.base_url) {
		throw 'Required CAS option `base_url` missing.';
	}
	this.base_url = options.base_url;
	this.systemId = options.systemId;
	this.service = options.service;
	this.employFlag = options.EmployFlag || "0";
	this.context_path = options.context_path || "/";
	this.setJSPath();
};

CAS.prototype.setJSPath = function() {
	var js = document.scripts;
	var jsPath;
	for (var i = 0; i < js.length; i++) {
		if (js[i].src.indexOf("cas_ajax.js") > -1) {
			jsPath = js[i].src.substring(0, js[i].src.lastIndexOf("/") + 1);
		}
	}
	this.jsPath = jsPath;
};

CAS.prototype.authenticate = function(callback) {
	var casObj = this;
	var service = this.service;
	if (!service) {
		service = window.location.protocol + "//" + window.location.hostname + ":" + window.location.port + window.location.pathname;
	}
	var serverUrl = this.base_url + '/ajaxLogin?service=' + encodeURIComponent(service);
	var userInfo = casObj.retrieveUserInfo();
	if(userInfo){
		callback(true, userInfo);
		return;
	}else{
		this.retrieveResponseFromServer(serverUrl, null, function(data){
			if(data.isLogin && data.ticket){
				if(casObj.loginValidate(data.ticket)){
					userInfo = casObj.retrieveUserInfo();
					if(userInfo){
						callback(true, userInfo);
						return;
					}
				}
			}else{
				callback(true, null, errorMsg);
				return;
			}
		});
	}
	callback(false);
};

CAS.prototype.realLogin = function(loginParam, callback) {
	var casObj = this;
	loginParam.systemId = this.systemId;
	loginParam.employFlag = this.employFlag;
	var code = this.retrieveSessionAuthCode();
	if(loginParam.authCode != code){
		return;
	}
	var service = this.service;
	if (!service) {
		service = window.location.protocol + "//" + window.location.hostname + ":" + window.location.port + window.location.pathname;
	}
	var serverUrl = this.base_url + '/ajaxRealLogin?service=' + encodeURIComponent(service);
	this.retrieveResponseFromServer(serverUrl, loginParam, function(data){
		if(data.isLogin && data.ticket){
			if(casObj.loginValidate(data.ticket)){
				var userInfo = casObj.retrieveUserInfo();
				if(userInfo){
					callback(true, userInfo);
					return;
				}
			}
		}
		callback(data.isLogin, null, data.errorMsg);
	});
};

CAS.prototype.retrieveUserInfo = function(){
	var serverUrl = this.getContextPath() + 'ajaxUserInfoRetireve?.tmp='+Math.random();
	var result;
	$.ajaxSetup({  
	    async : false  
	});
	$.get(serverUrl, function(data, status) {
		if(data){
			result = data;
		}
	});
	result = result && JSON.parse(result);
	return result;
};

CAS.prototype.getContextPath = function(){
	var result = "";
	if(this.context_path == "/"){
		return this.context_path;
	}
	if(this.context_path.indexOf("/") == 0){
		result += this.context_path;
	}else{
		result += "/" + this.context_path;
	}
	if(this.context_path.charAt(this.context_path.length-1)!="/"){
		result += "/";
	}
	return result;
};

CAS.prototype.authCodePath = function(){
	return this.getContextPath() + "ajaxCaptchaImageRetireve?.tmp="+Math.random();
};

CAS.prototype.changeAuthCode = function(authCodeId, captchaMsgId){
	$("#" + authCodeId).attr("src", this.authCodePath());
	this.changeAuthCodeMsg(captchaMsgId);
};

CAS.prototype.changeAuthCodeMsg = function(captchaMsgId){
	if($("#" + captchaMsgId).attr("src") != ""){
		$("#" + captchaMsgId).attr("src", this.jsPath + "/captcha_message_fail.gif");
	}
};

CAS.prototype.changeAuthCodeCheck = function(authCodeInputId, captchaMsgId){
	var value=$("#" + authCodeInputId).val();
	if(value.length==4){
		if((/[\u4e00-\u9fa5]+/).test(value)) {
			value = encodeURI(encodeURI(value));
		}
		var code = this.retrieveSessionAuthCode();
		$("#" + captchaMsgId).css('display','');
		if(value == code){
			$("#" + captchaMsgId).attr("src", this.jsPath + "/captcha_message_succ.gif");
		}else{
			$("#" + captchaMsgId).attr("src", this.jsPath + "/captcha_message_fail.gif");
		}
	}else{
		$("#" + captchaMsgId).css('display','none');
	}
};

CAS.prototype.retrieveSessionAuthCode = function(){
	var result;
	$.ajaxSetup({   
        async : false  
    }); 
	$.get(this.getContextPath() + 'ajaxAuthCodeRetireve?.tmp='+Math.random(), function(data, status) {  
		result = data;
	});
	return result;
};

CAS.prototype.loginValidate = function(ticket){
	var serverUrl = this.getContextPath() + '?loginType=ajax&ticket=' + ticket + "&service=" + this.service;
	var result;
	$.ajaxSetup({  
	    async : false  
	});
	$.get(serverUrl, function(data, status) {  
	    result = data;
	});
	return result == "success";
};

CAS.prototype.retrieveResponseFromServer = function(serverUrl, dataObj, callback) {
	dataObj = {"data":encodeURI(JSON.stringify(dataObj))};
	$.ajax({
		type : "GET",
		async : true,
		timeout : 5000,
		url : serverUrl,
		dataType : "jsonp",
		data : dataObj,
		jsonp : "callback",// 传递给请求处理程序或页面的，用以获得jsonp回调函数名的参数名(一般默认为:callback)
		crossDomain: true,
		xhrFields: {
			// 如果你想向服务器发送cookies的话，设置withCredentials为true
			// 而且你的服务器必须返回头部带有'Access-Control-Allow-Credentials:true'的回应
			withCredentials: true
		},
		success : function(response){
			callback(response);
		},// 自定义的jsonp回调函数名称，默认为jQuery自动生成的随机函数名，也可以写"?"，jQuery会自动为你处理数据
		error : function(xmlObj, errorMsg, exceptionObj) {
			if ("timeout" == errorMsg) {
				alert("服务器连接失败，请检查网络连接和系统配置。");
			}
		}
	});
};